package com.ledim.activity;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ledim.activity.base.LedimBaseGridViewActivity;
import com.ledim.adapter.ChannelEpisodeAdapter;
import com.ledim.adapter.base.LedimBaseListAdapter;
import com.ledim.bean.ChannelFilterHeadBean;
import com.ledim.bean.FilterListBean;
import com.ledim.bean.FilterValBean;
import com.ledim.bean.LedimCardGroupBean;
import com.ledim.bean.LedimChoiceCardBean;
import com.ledim.bean.TagChannelListDataResponse;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.ledimview.FilterTabsView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.DensityUtil;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.loadmore.GridViewWithHeaderAndFooter;
import com.ledim.widget.view.LoadingBar;
import com.ledim.widget.view.TagFilterCallbackListener;
import com.letv.android.young.client.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 频道标签页
 */
public class LedimChannelsActivity extends LedimBaseGridViewActivity
        implements TagFilterCallbackListener {

    public static final String CARDID = "card_id";
    public static final String CARD_FROM = "card_from";
    public static final int FORM_TAG_TEXT = 0;//从首页点击渠道标签条目
    public static final int FORM_GET_MORE = 1;//从首页点击获取更多
    private static final int CHANNEL_FIVE = 5;
    private ImageView mBack;
    private TextView mTitle;
    private TextView mCondition;
    private FilterTabsView mChannelTabsView;
    private View mConditionLayout;
    private LedimChoiceCardBean mCard;
    private String mCategoryId = "1";
    private String mCategoryType;
    private ArrayList<FilterListBean> mFilters = new ArrayList<FilterListBean>();
    private LedimCardGroupBean mCardGroupBean;
    private int mType;
    private String cid;
    private FilterValBean srFilter;
    private FilterValBean stFilter;
    private FilterValBean scFilter;
    private FilterValBean arFilter;
    private FilterValBean yrFilter;
    private FilterValBean vtFilter;
    private FilterValBean agFilter;
    private FilterValBean spFilter;
    private ChannelFilterHeadBean headDataList;
    private LoadingBar mLoadingBar;
    private Map<String, String> queryMap = new HashMap<String, String>();
    private rx.Observer mObsevers;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_channels;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected boolean enterAutoLoadData() {
        return false;
    }

    @Override
    protected LedimBaseListAdapter getAdapter() {
        return new ChannelEpisodeAdapter(this);
    }

    @Override
    protected void getDatas() {
        if (mObsevers == null) {
            mObsevers = new LedimHttpObserver<TagChannelListDataResponse>() {
                @Override
                public void onCompleted() {
                    super.onCompleted();
                }

                @Override
                public void onNext(TagChannelListDataResponse data) {
                    if (mLoadingBar != null) {
                        mLoadingBar.dismiss();
                    }
                    super.onNext(data);
                    if (data != null && data.success) {
                        initTotalPages(data.paged.total);
                        setDatas(data.data, data.paged.more);
                    } else {
                        setServerDataError();
                    }

                }

                @Override
                public void onError(Throwable e) {
                    if (mLoadingBar != null) {
                        mLoadingBar.dismiss();
                    }
                    super.onError(e);
                    setServerDataError();
                }
            };
        }
        LedimApiServiceFactory.createService(ApiService.class)
                              .getChannelListData(mCategoryId, mLoadPage +
                                      1, getPageSize(), queryMap)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io()).subscribe(mObsevers);
    }

    @Override
    protected int getNumColumns() {
        return 2;
    }

    private void initView() {
        mBack = findViewByIdExt(R.id.iv_back);
        mTitle = findViewByIdExt(R.id.tv_title);
        // mBgView = findViewById(R.id.top_view_bg);
        mCondition = (TextView) findViewById(R.id.conditions);
        mConditionLayout = findViewById(R.id.conditions_layout);
        mChannelTabsView = (FilterTabsView) View.inflate(this, R.layout.channels_tabs_layout, null);

        // mBgView.setBackgroundColor(Color.parseColor("#FAED4D"));
        mBack.setVisibility(View.VISIBLE);
        mBack.setOnClickListener(this);

        mType = getIntent().getIntExtra(CARD_FROM, 0);
        if (mType == FORM_TAG_TEXT) {
            mCard = (LedimChoiceCardBean) getIntent().getSerializableExtra(CARDID);
        } else if (mType == FORM_GET_MORE) {
            mCardGroupBean = (LedimCardGroupBean) getIntent().getSerializableExtra(CARDID);
        }
        if (mType == FORM_TAG_TEXT && mCard != null) {
            mCategoryId = mCard.media;
            mCategoryType = mCard.title;
            mTitle.setText(mCategoryType);

        } else if (mType == FORM_GET_MORE && mCardGroupBean != null) {
            mCategoryId = mCardGroupBean.union_id;
            mCategoryType = mCardGroupBean.title;
            mTitle.setText(mCategoryType);
        }
        getHeadData(mCategoryId);
    }

    /**
     * 获取头部数据
     *
     * @param categoryId
     */
    public void getHeadData(String categoryId) {
        if (mLoadingBar == null) {
            mLoadingBar = new LoadingBar(this);
        }
        mLoadingBar.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .getHeadData(categoryId)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<ChannelFilterHeadBean>>() {

                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();

                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      if (mLoadingBar != null) {
                                          mLoadingBar.dismiss();
                                      }
                                      LogUtil.e(e.getMessage());

                                  }

                                  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                                  @Override
                                  public void onNext(
                                          BaseResultDataInfo<ChannelFilterHeadBean> baseResultDataInfo) {
                                      super.onNext(baseResultDataInfo);

                                      if (baseResultDataInfo != null) {
                                          if (baseResultDataInfo.success) {
                                              //成功
                                              cid = baseResultDataInfo.data.cid;
                                              headDataList = baseResultDataInfo.data;
                                              mFilters.clear();
                                              mFilters.addAll(baseResultDataInfo.data.filter);
                                              mChannelTabsView.bindData(mFilters, LedimChannelsActivity.this);
                                              ((GridViewWithHeaderAndFooter) mAdapterView).addHeaderView(mChannelTabsView);
                                              mAdapterView.setAdapter(mAdapter);
                                              getFirstFiltersData();
                                              mCondition.setText(getFilterText());

                                              int stateViewTopMargin =
                                                      baseResultDataInfo.data.filter.size() *
                                                              DensityUtil.dip2px(LedimChannelsActivity.this, 25);
                                              LogUtil.e("ccx stateViewTopMargin=" +
                                                      stateViewTopMargin);
                                              LinearLayout.LayoutParams params =
                                                      (LinearLayout.LayoutParams) mLedimStateView.getLayoutParams();
                                              params.setMargins(0, -stateViewTopMargin * 2, 0, 0);
                                              //mLedimStateView.setPadding(0, -stateViewTopMargin,
                                              //        0, 0);
                                              mAdapter.setOnScrollListener(new AbsListView.OnScrollListener() {
                                                  @Override
                                                  public void onScrollStateChanged(AbsListView view,
                                                                                   int scrollState) {

                                                  }

                                                  @Override
                                                  public void onScroll(AbsListView view,
                                                                       int firstVisibleItem,
                                                                       int visibleItemCount,
                                                                       int totalItemCount) {
                                                      if (firstVisibleItem >= 2) {
                                                          mConditionLayout.setVisibility(View.VISIBLE);
                                                      } else {
                                                          mConditionLayout.setVisibility(View.GONE);
                                                      }

                                                  }
                                              });
                                          } else {
                                              if (mLoadingBar != null) {
                                                  mLoadingBar.dismiss();
                                              }
                                              ToastUtil.toast(baseResultDataInfo.message);
                                          }
                                      } else {
                                          if (mLoadingBar != null) {
                                              mLoadingBar.dismiss();
                                          }
                                      }
                                  }
                              });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    //默认筛选条件
    private void getFirstFiltersData() {
        //第一次请求的时候，每行默认的都是第一个
        queryMap.put("opposite", "0");
        queryMap.put("vt", null);
        for (int i = 0; i < headDataList.filter.size(); i++) {
            FilterListBean filterBean = headDataList.filter.get(i);
            ArrayList<FilterValBean> filterVal = filterBean.val;
            if (filterVal != null && filterVal.size() > 0) {
                FilterValBean filterValBean = filterVal.get(0);
                if (filterBean.key.equals("sr")) {
                    queryMap.put("sr", filterValBean.id);
                    srFilter = filterValBean;
                }
                if (filterBean.key.equals("st")) {
                    queryMap.put("st", filterValBean.id);
                    stFilter = filterValBean;
                    //对st的进行判断
                    if (filterBean.val.size() > 0) {
                        String mKey = filterBean.val.get(0).key;
                        if (!TextUtils.isEmpty(mKey) && mKey.equals("vt")) {
                            queryMap.put("vt", filterBean.val.get(0).id);
                            queryMap.put("st", null);
                        }
                        if (TextUtils.isEmpty(mKey)) {
                            queryMap.put("st", filterBean.val.get(0).id);
                            queryMap.put("vt", null);
                        }
                    }
                }
                if (filterBean.key.equals("vt")) {
                    queryMap.put("vt", filterValBean.id);
                    vtFilter = filterValBean;
                }
                if (filterBean.key.equals("ag")) {
                    queryMap.put("ag", filterValBean.id);
                    agFilter = filterValBean;
                }
                if (filterBean.key.equals("sp")) {
                    queryMap.put("sp", filterValBean.id);
                    spFilter = filterValBean;
                }
                if (filterBean.key.equals("sc")) {
                    queryMap.put("sc", filterValBean.id);
                    scFilter = filterValBean;
                }
                if (filterBean.key.equals("ar")) {
                    queryMap.put("ar", filterValBean.id);
                    arFilter = filterValBean;
                }
                if (filterBean.key.equals("yr")) {
                    queryMap.put("yr", filterValBean.id);
                    yrFilter = filterValBean;
                }
                if (filterBean.val.size() > 0 &&
                        !TextUtils.isEmpty(filterBean.val.get(0).opposite)) {
                    queryMap.put("opposite", filterBean.val.get(0).opposite);
                }
            }

        }
        getDatas();
    }

    /**
     * listview回调
     *
     * @param filterBean
     * @param valueBean
     */
    @Override
    public void onFilter(FilterListBean filterBean, FilterValBean valueBean) {

        String mOpposite = valueBean.opposite;
        if (filterBean.key.equals("sr")) {
            queryMap.put("sr", valueBean.id);
            srFilter = valueBean;
        } else if (filterBean.key.equals("st")) {
            //对st的进行判断
            String mKey = valueBean.key;
            if (!TextUtils.isEmpty(mKey) && mKey.equals("vt")) {
                queryMap.put("vt", valueBean.id);
                queryMap.put("st", null);
            }
            if (TextUtils.isEmpty(mKey)) {
                queryMap.put("st", valueBean.id);
                queryMap.put("vt", null);
            }
            stFilter = valueBean;
        } else if (filterBean.key.equals("sc")) {
            queryMap.put("sc", valueBean.id);
            scFilter = valueBean;

        } else if (filterBean.key.equals("ar")) {
            queryMap.put("ar", valueBean.id);
            arFilter = valueBean;

        } else if (filterBean.key.equals("yr")) {
            queryMap.put("yr", valueBean.id);
            yrFilter = valueBean;

        } else if (filterBean.key.equals("vt")) {
            queryMap.put("vt", valueBean.id);
            vtFilter = valueBean;

        } else if (filterBean.key.equals("ag")) {
            queryMap.put("ag", valueBean.id);
            agFilter = valueBean;

        } else if (filterBean.key.equals("sp")) {
            queryMap.put("sp", valueBean.id);
            spFilter = valueBean;
        }

        if (!TextUtils.isEmpty(mOpposite)) {
            queryMap.put("opposite", mOpposite);
        }
        mItems.clear();
        mAdapter.notifyDataSetChanged();
        mLoadingBar.show();
        pullRefresh();
        mCondition.setText(getFilterText());
    }

    private String getFilterText() {
        StringBuilder filters = new StringBuilder();
        if (srFilter != null) {
            if (!srFilter.name.equals("全部")) {
                filters.append(srFilter.name).append(" • ");
            }
        }
        if (stFilter != null) {
            if (!stFilter.name.equals("全部")) {
                filters.append(stFilter.name).append(" • ");
            }
        }
        if (scFilter != null) {
            if (!scFilter.name.equals("全部")) {
                filters.append(scFilter.name).append(" • ");
            }
        }
        if (arFilter != null) {
            if (!arFilter.name.equals("全部")) {
                filters.append(arFilter.name).append(" • ");
            }
        }
        if (yrFilter != null) {
            if (!yrFilter.name.equals("全部")) {
                filters.append(yrFilter.name).append(" • ");
            }
        }

        if (vtFilter != null) {
            if (!vtFilter.name.equals("全部")) {
                filters.append(vtFilter.name).append(" • ");
            }
        }

        if (agFilter != null) {
            if (!agFilter.name.equals("全部")) {
                filters.append(agFilter.name).append(" • ");
            }
        }

        if (spFilter != null) {
            if (!spFilter.name.equals("全部")) {
                filters.append(spFilter.name).append(" • ");
            }
        }
        if (filters.toString().length() > 0) {
            return filters.toString().substring(0, filters.lastIndexOf(" • "));
        }
        return null;
    }

    protected boolean enablePullRefresh() {
        return false;
    }

    @Override
    protected void onDestroy() {
        if (mLoadingBar.isShowing()) {
            mLoadingBar.dismiss();
        }
        super.onDestroy();
    }

}



